#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <signal.h>
#include <pthread.h>

#include "log.hpp"
#include "Task.hpp"
#include "ThreadPool.hpp"


namespace server
{
    enum
    {
        USAGE_ERR = 1,
        SOCKET_ERR,
        BIND_ERR,
        LISTEN_ERR
    };

    static const uint16_t gport = 8080;
    static const int gbacklog = 5;

    class TcpServer;
    class ThreadData
    {
    public:
        ThreadData(TcpServer *self, int sock)
            : _self(self), _sock(sock)
        {
        }

    public:
        TcpServer *_self;
        int _sock;
    };

    class TcpServer
    {
    public:
        TcpServer(const uint16_t &port = gport)
            : _listensock(-1), _port(port)
        {
        }
        void initServer()
        {
            // 1.创建socket文件套接字对象
            _listensock = socket(AF_INET, SOCK_STREAM, 0);
            if (_listensock < 0)
            {
                logMessage(FATAL, "create socket error");
                exit(SOCKET_ERR);
            }
            // 2.bind绑定自己的网络信息
            struct sockaddr_in local;
            memset(&local, 0, sizeof(local));
            local.sin_family = AF_INET;
            local.sin_port = htons(_port);//固定端口
            local.sin_addr.s_addr = INADDR_ANY;//任意ip
            if (bind(_listensock, (struct sockaddr *)&local, sizeof(local)), 0)
            {
                logMessage(FATAL, "bind socket error");
                exit(BIND_ERR);
            }
             logMessage(NORMAL, "bind socket success");

            // 3.设置soket为监听状态
            if (listen(_listensock, gbacklog) < 0)
            {
                logMessage(FATAL, "listen socket error");
                exit(LISTEN_ERR);
            }
            logMessage(NORMAL, "listen socket success");

        }
        void start()
        {
             //4.线程池初始化
            ThreadPool<Task>::getInstance()->run();
            
            for (;;)
            {
                // 4.获取新链接
                // sock和client通信的fd
                struct sockaddr_in peer;
                socklen_t len = sizeof(peer);
                int sock = accept(_listensock, (struct sockaddr *)&peer, &len);
                if (sock < 0)
                {
                    logMessage(ERROR, "accept error ,next");
                    continue;
                }
                logMessage(NORMAL, "accept a new link success");
                std::cout << "sock: " << sock << std::endl;

                // 5.这里就是一个sock，未来通信就可以用这个面向字节流的sock,后续全部都是文件操作
                // verson 1
                /*
                serviceIO(sock);
                close(sock);
                */

                // verson 2 多进程版
                // 父进程阻塞等待，会让执行流依旧是串行操作，没有效率的提升
                /*
                pid_t id=fork();
                if(id==0)//child
                {
                    close(_listensock);//关掉非必须的文件描述符
                    if(fork()>0) exit(0);//子进程被回收，由孙子进程执行，执行完毕后退出，变成孤儿进程，由操作系统领养回收
                    serviceIO(sock);
                    close(sock);
                    exit(0);
                }
                close(sock);//文件引用计数减一
                //father
                pid_t ret=waitpid(id,nullptr,0);
                if(ret>0)
                {
                    std::cout<<"waitsuccess: "<<ret<<std::endl;
                }
                */
 
                // verson 3 多线程版
                /*
                pthread_t tid;
                ThreadData* td=new ThreadData(this,sock);
                pthread_create(&tid,nullptr,threadRoutine,td);
                //是否要进行线程等待，不需要，怎么解决？
                //进行线程分离
                */

                // verson 4 线程池版
                ThreadPool<Task>::getInstance()->push(Task(sock, serviceIO));
            }
        }

        /*
        static void* threadRoutine(void* args)
        {
            //进行线程分离，主线程不需要join，在该线程退出时，自动释放该线程资源
            pthread_detach(pthread_self());
            ThreadData* td=static_cast<ThreadData*>(args);
            td->_self->serviceIO(td->_sock);
            close(td->_sock);//使用完毕之后，关闭sock，防止文件描述符资源泄漏
            delete td;
            return nullptr;
        }
        */

        ~TcpServer()
        {
        }

    private:
        int _listensock; // 不是用来进行数据通信的，是用来监听链接到来获取链接的
        uint16_t _port;
    };
}